from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView
from rest_framework.mixins import CreateModelMixin, DestroyModelMixin, ListModelMixin, UpdateModelMixin, RetrieveModelMixin
from rest_framework import status, serializers
from .serializers import  UserCaptchaCreateSerializer, UserCreateSerailizer, UserLoginSerializer
from utils.my_mail import my_send_mail
from .tasks import reg_send_mail
from rest_framework_jwt.settings import api_settings
from django.contrib.auth import authenticate
from .models import UserInfo
from music_lzz.settings import EMAIL_HOST_USER
# Create your views here.
# class UserRegisterViewSet(CreateModelMixin, GenericViewSet)


class UserCreateCaptchaViewSet(CreateModelMixin, GenericViewSet):
    queryset =  UserCaptchaCreateSerializer.Meta.model.objects.all()
    serializer_class =  UserCaptchaCreateSerializer

    def perform_create(self, serializer):
        data = serializer.validated_data
        serializer.save()
        captcha = '你的验证码为{}'.format(data['captcha'])
        title = '网易云验证码'
        # my_send_mail(title=title, context=captcha,to_email=data['email'], EMAIL_HOST_USER=EMAIL_HOST_USER)
        reg_send_mail.delay(title=title, context=captcha, from_email=EMAIL_HOST_USER, to_email=data['email'])
        return super().perform_create(serializer)


class CreateUserViewSet(CreateModelMixin, GenericViewSet):
    serializer_class = UserCreateSerailizer
    queryset = UserCreateSerailizer.Meta.model.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return Response({'token': token}, status=status.HTTP_201_CREATED, headers=headers)

    def perform_create(self, serializer):
        return serializer.save()


class UserLoginView(APIView):

    def post(self,request):
        data = UserLoginSerializer(data=request.POST)
        if not data.is_valid():
            raise serializers.ValidationError(data.errors)
        vali_data = data.validated_data
        user = authenticate(**vali_data)
        if not user:
            raise serializers.ValidationError({'error':'用户名或者密码错误'})
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        return Response({'token':token})




